#!/bin/bash

set -e

echo "=========================================="
echo "部署 Behavior Processor Lambda 到 LocalStack"
echo "=========================================="

# 加载 .env 文件
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"

if [ -f "$PROJECT_ROOT/.env" ]; then
    echo "📝 加载环境变量..."
    set -a
    source "$PROJECT_ROOT/.env"
    set +a
    echo "   LLM_API_KEY: ${LLM_API_KEY:0:10}..."
fi

EVENT_PROCESSOR_DIR="$PROJECT_ROOT/event-processor"
TEMP_DIR="/tmp/browse-etl-behavior-processor"
DEPS_CACHE_DIR="/tmp/browse-etl-behavior-processor-deps"

# 检查必要文件
if [ ! -f "$EVENT_PROCESSOR_DIR/lambda_handler.py" ]; then
    echo "❌ 错误: lambda_handler.py 不存在"
    exit 1
fi

# 创建临时目录
rm -rf "$TEMP_DIR"
mkdir -p "$TEMP_DIR"

# 复制 Lambda 代码
echo "📦 打包 Lambda 函数..."
cp "$EVENT_PROCESSOR_DIR/lambda_handler.py" "$TEMP_DIR/"
cp "$EVENT_PROCESSOR_DIR/core.py" "$TEMP_DIR/"
cp "$EVENT_PROCESSOR_DIR/database.py" "$TEMP_DIR/"
cp "$EVENT_PROCESSOR_DIR/llm_client.py" "$TEMP_DIR/"
cp "$EVENT_PROCESSOR_DIR/prompt_template_v2.txt" "$TEMP_DIR/"
cp "$EVENT_PROCESSOR_DIR/schema.sql" "$TEMP_DIR/"
cp "$EVENT_PROCESSOR_DIR/requirements.txt" "$TEMP_DIR/"

cd "$TEMP_DIR"

# 计算依赖哈希
REQUIREMENTS_HASH=$(md5 -q requirements.txt 2>/dev/null || md5sum requirements.txt | cut -d' ' -f1)
CACHE_MARKER="$DEPS_CACHE_DIR/$REQUIREMENTS_HASH/.cache_complete"

# 安装依赖
if [ -f "$CACHE_MARKER" ]; then
    echo "✅ 使用缓存的依赖（hash: ${REQUIREMENTS_HASH:0:8}...）"
    cd "$DEPS_CACHE_DIR/$REQUIREMENTS_HASH"
    for item in *; do
        if [ -f "$TEMP_DIR/$item" ]; then
            continue
        fi
        cp -r "$item" "$TEMP_DIR/"
    done
    cd "$TEMP_DIR"
else
    echo "📥 安装依赖（使用 Lambda 兼容环境）..."
    # 使用 Docker Python 容器在 Linux 环境安装依赖，确保与 Lambda 兼容
    docker run --rm \
        -v "$TEMP_DIR":/work \
        -w /work \
        python:3.12-slim \
        bash -c "pip install -r requirements.txt -t . --upgrade --no-cache-dir"

    # 缓存依赖包
    echo "💾 缓存依赖..."
    mkdir -p "$DEPS_CACHE_DIR/$REQUIREMENTS_HASH"
    for item in *; do
        if [ -f "$EVENT_PROCESSOR_DIR/$item" ]; then
            continue
        fi
        cp -r "$item" "$DEPS_CACHE_DIR/$REQUIREMENTS_HASH/" 2>/dev/null || true
    done
    touch "$CACHE_MARKER"
fi

# 创建部署包
echo "🗜️  创建部署包..."
zip -r function.zip . -q

# 复制到可访问位置
cp function.zip /tmp/behavior-processor-lambda.zip

echo "☁️  部署到 LocalStack..."

# 将zip文件复制到容器
docker cp /tmp/behavior-processor-lambda.zip browse-etl-localstack:/tmp/behavior-processor.zip

# 检查 LocalStack 是否运行
if ! docker ps | grep -q browse-etl-localstack; then
    echo "❌ 错误: LocalStack 容器未运行"
    echo "💡 提示: 先运行 make start"
    exit 1
fi

# 部署 Lambda 函数
echo "📤 创建/更新 Lambda 函数..."

# 设置默认值
LLM_PROVIDER=${LLM_PROVIDER:-deepseek}
LLM_API_KEY=${LLM_API_KEY:-}
LLM_API_URL=${LLM_API_URL:-https://api.deepseek.com/v1/chat/completions}
LLM_MODEL=${LLM_MODEL:-deepseek-chat}

# 构建环境变量 JSON
cat > /tmp/lambda-env.json <<EOF
{
  "Variables": {
    "AWS_ENDPOINT": "http://localstack:4566",
    "AWS_REGION": "us-east-1",
    "POSTGRES_HOST": "postgres",
    "POSTGRES_PORT": "5432",
    "POSTGRES_DB": "behavior_analysis",
    "POSTGRES_USER": "postgres",
    "POSTGRES_PASSWORD": "postgres",
    "LLM_PROVIDER": "$LLM_PROVIDER",
    "LLM_API_KEY": "$LLM_API_KEY",
    "LLM_API_URL": "$LLM_API_URL",
    "LLM_MODEL": "$LLM_MODEL"
  }
}
EOF

# 复制环境变量文件到容器
docker cp /tmp/lambda-env.json browse-etl-localstack:/tmp/lambda-env.json

# 尝试创建 Lambda 函数
docker exec browse-etl-localstack awslocal lambda create-function \
  --function-name behavior-processor \
  --runtime python3.12 \
  --handler lambda_handler.lambda_handler \
  --zip-file fileb:///tmp/behavior-processor.zip \
  --role arn:aws:iam::000000000000:role/LambdaExecutionRole \
  --environment file:///tmp/lambda-env.json \
  --timeout 300 \
  --memory-size 512 \
  --region us-east-1 2>/dev/null

# 如果创建失败（函数已存在），更新代码和环境变量
if [ $? -ne 0 ]; then
  echo "   Lambda 已存在，更新代码和环境变量..."

  # 更新代码
  docker exec browse-etl-localstack awslocal lambda update-function-code \
    --function-name behavior-processor \
    --zip-file fileb:///tmp/behavior-processor.zip \
    --region us-east-1 >/dev/null 2>&1

  # 更新环境变量
  docker exec browse-etl-localstack awslocal lambda update-function-configuration \
    --function-name behavior-processor \
    --environment file:///tmp/lambda-env.json \
    --region us-east-1 >/dev/null 2>&1
fi

echo "✅ Lambda 函数已部署"

# 创建 Kinesis Event Source Mapping
echo "🔗 配置 Kinesis 触发器..."

# 获取 Stream ARN（带重试）
echo "   获取 Stream ARN..."
STREAM_ARN=""
for i in {1..10}; do
    STREAM_ARN=$(docker exec browse-etl-localstack awslocal kinesis describe-stream \
      --stream-name click-events-stream \
      --region us-east-1 \
      --query 'StreamDescription.StreamARN' --output text 2>/dev/null || echo "")

    if [ -n "$STREAM_ARN" ] && [ "$STREAM_ARN" != "None" ]; then
        echo "   Stream ARN: $STREAM_ARN"
        break
    fi

    if [ $i -lt 10 ]; then
        echo "   等待 Kinesis 服务就绪... ($i/10)"
        sleep 2
    else
        echo "❌ 错误: 无法获取 Stream ARN，Kinesis 服务可能未就绪"
        exit 1
    fi
done

# 检查是否已有 Event Source Mapping
EXISTING_UUID=$(docker exec browse-etl-localstack awslocal lambda list-event-source-mappings \
  --function-name behavior-processor \
  --region us-east-1 \
  --query 'EventSourceMappings[0].UUID' --output text 2>/dev/null || echo "")

if [ "$EXISTING_UUID" != "" ] && [ "$EXISTING_UUID" != "None" ]; then
    echo "   更新现有触发器..."
    docker exec browse-etl-localstack awslocal lambda update-event-source-mapping \
      --uuid "$EXISTING_UUID" \
      --batch-size 20 \
      --maximum-batching-window-in-seconds 5 \
      --region us-east-1 >/dev/null
else
    echo "   创建新触发器..."
    docker exec browse-etl-localstack awslocal lambda create-event-source-mapping \
      --function-name behavior-processor \
      --event-source-arn "$STREAM_ARN" \
      --batch-size 20 \
      --maximum-batching-window-in-seconds 5 \
      --starting-position LATEST \
      --region us-east-1 >/dev/null
fi

echo "✅ Kinesis 触发器已配置"

# 清理
rm -rf "$TEMP_DIR"
rm -f /tmp/behavior-processor-lambda.zip

echo ""
echo "=========================================="
echo "✅ Behavior Processor Lambda 部署完成！"
echo "=========================================="
echo ""
echo "Lambda 函数: behavior-processor"
echo "触发器: Kinesis (click-events-stream)"
echo "批次大小: 20 events"
echo ""
echo "💡 提示: 现在可以使用 make test 发送测试事件"
echo "=========================================="
